package com.practice.springboot_01_zwj.controller;

import com.practice.springboot_01_zwj.entity.HealthyEightRate;
import com.practice.springboot_01_zwj.scheduled.FileImportService;
import com.practice.springboot_01_zwj.service.HealthyEightRateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/healthy")
public class HealthyEightRateController {

    @Autowired
    private HealthyEightRateService healthyEightRateService;
    @Autowired
    private FileImportService fileImportService;

    @RequestMapping("/selectAll")
    public List<HealthyEightRate> selectAll(){
        return healthyEightRateService.selectHealthyEightRateAll();
    }

    @PostMapping("/selectByCityCode")
    public HealthyEightRate selectByCityCode(@RequestBody HealthyEightRate request) {
        return healthyEightRateService.selectByCityCode(request.getCityCode());
    }
    /**
     * 手动触发文件导入任务
     */
    @PostMapping("/fileImport")
    public ResponseEntity<Map<String, Object>> executeFileImport() {
        Map<String, Object> response = new HashMap<>();

        try {
            // 记录开始时间
            long startTime = System.currentTimeMillis();

            // 执行文件导入任务
            fileImportService.executeFileImport();

            // 计算执行时间
            long executionTime = System.currentTimeMillis() - startTime;

            response.put("success", true);
            response.put("message", "文件导入任务执行成功");
            response.put("executionTime", executionTime + "ms");
            response.put("timestamp", new Date());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "文件导入任务执行失败: " + e.getMessage());
            response.put("timestamp", new Date());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(response);
        }
    }

    /**
     * 获取任务状态（可选）
     * GET请求：http://localhost:8080/api/task/status
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getTaskStatus() {
        Map<String, Object> response = new HashMap<>();
        response.put("service", "文件导入服务");
        response.put("status", "运行中");
        response.put("nextScheduledTime", "每天 07:00 AM");
        response.put("timestamp", new Date());

        return ResponseEntity.ok(response);
    }
}

